package cn.doitedu.day02

import org.apache.spark.rdd.{RDD, ShuffledRDD}
import org.apache.spark.{Aggregator, HashPartitioner, SparkConf, SparkContext}

import scala.collection.mutable.ArrayBuffer
//使用ShuffledRDD实现groupByKey的功能
object T16_ShuffledRDDDemo2{

  def main(args: Array[String]): Unit = {

    //1.创建SparkConf
    val conf = new SparkConf().setAppName("MapPartitionsWithIndexDemo")
      .setMaster("local[4]")

    //2.创建SparkContext
    val sc = new SparkContext(conf)

    val lst = List(
      ("spark", 1), ("hadoop", 1), ("hive", 1), ("spark", 1),
      ("spark", 1), ("flink", 1), ("hbase", 1), ("spark", 1),
      ("kafka", 1), ("kafka", 1), ("kafka", 1), ("kafka", 1),
      ("hadoop", 1), ("flink", 1), ("hive", 1), ("flink", 1)
    )
    //通过并行化的方式创建RDD，分区数量为4
    val wordAndOne: RDD[(String, Int)] = sc.parallelize(lst, 4)

    val shuffledRDD = new ShuffledRDD[String, Int, ArrayBuffer[Int]](wordAndOne, new HashPartitioner(wordAndOne.partitions.length))

    val f1 = (v: Int) => ArrayBuffer[Int](v)
    val f2 = (ab: ArrayBuffer[Int], v2: Int) => ab += v2
    val f3 = (ab1: ArrayBuffer[Int], ab2: ArrayBuffer[Int]) => ab1 ++= ab2

    val aggregator = new Aggregator[String, Int, ArrayBuffer[Int]](
      f1, f2, f3
    )
    shuffledRDD.setAggregator(aggregator)

    shuffledRDD.setMapSideCombine(true)

    shuffledRDD.saveAsTextFile("out/out04")

  }


}
